<?php

namespace app\index\controller;

use app\index\service\CompanyService;
use app\index\service\ExportService;
use app\admin\service\IncreaseService;
use app\admin\validate\Increase as IncreaseValidate;
use app\admin\service\IncreaseService as AdmIncService;
use app\admin\service\DownsizingService as AdmDowService;
use library\Controller;
use think\Db;

/**
 * 员工管理
 * Class Staff
 * @package app\index\controller
 */
class Staff extends Base
{
	 	
    /**
     * 员工列表
     */
    public function index()
    {
        $where[] = ['cp.company_id','eq',$this->company['id']];
        $status = $this->request->get('status');
        if (in_array($status, [1,2])){
        	if($status == 2){
        		$where[] = ['cp.status','in',[2,3]];
        	}else{
        		$where[] = ['cp.status','eq',1];
        	}          
        }
        $search = $this->request->get('title');
        if ($search){
            $where[] = ['i.name|i.id_number','like','%'.$search.'%'];
        }
		$list = Db::name('system_company_person')
				->alias('cp')
				->join('system_increase i','cp.increase_id = i.id')
				->where($where)
				->field('cp.increase_id,cp.person_id,cp.person_code,cp.status,i.name,i.id_number,i.mobile')
    			->order('cp.id desc')
    			->paginate(10,false,['query'=>request()->param(),'type' => 'page\Page','var_page'  => 'page']);
		$this ->list = $list; 	
        $this->fetch();
    }


	 /**
     * 员工详情
     */
    public function detail()
    {
    	$id = $this->request->get('id');
		$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
		if(!$increase){
			$this->redirect('index/publicot/transition', ['info'=>'暂无员工信息','type'=>'1']);
		}
		$insurances = Db::name('system_insurance_log')->where(['increase_id'=>$id])->field('insurance,wage,company_base,personal_base,status,start_date,end_date,cancel_date')->order('insurance asc')->select();
		if($insurances){
			foreach($insurances as $k=>$v){
				$insurances[$k]['insurance'] = get_option('insurance')[$v['insurance']];
				$insurances[$k]['status_cn'] = ['1'=>'在保 ','2'=>'解约','3'=>'停保'][$v['status']];
				if($v['status'] == 2){
					$insurances[$k]['end_date'] = $v['cancel_date'];
				}
			}
		}
		$this ->info = $increase;
		$this ->list = $insurances; 	
        $this->fetch();
    }

	/**
	 * 根据工资获取所有基数
	 */
	public function insuranceAllBase(){
		$wage = $this->request->post('wage');
		if(!is_numeric($wage)){
			$this->error('参数错误');
		}
		$data = IncreaseService::allBase($wage);
		$this->success('获取成功',$data);	
	}
	
	
	/**
	 * 根据工资获取单一基数
	 */
	public function insuranceBase(){
		$wage = $this->request->post('wage');
		$insurance = $this->request->post('insurance');			
		if(!is_numeric($wage) || !in_array($insurance, [1,2,3,4,5])){
			$this->error('参数错误');
		}
		$data = IncreaseService::oneBase($insurance,$wage);
		$this->success('获取成功',$data);
	}
	

	 /**
     * 增加险种
     */
    public function increase()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
			trim_array($data);
			$increase = Db::name('system_increase')->where(['id'=>$data['increase_id'],'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->error('暂无员工信息');
			}
			$person = Db::name('system_person')->where(['id'=>$increase['person_id'],'company_id'=>$this->company['id']])->find();
			if(!$person || in_array($person['status'], [2,3])){
				$this->error('该员工不在职，无法增加险种');
			}
			$find = Db::name('system_downsizing')->where(['person_id'=>$increase['person_id'],'status'=>[1,3],'is_deleted'=>0])->find();
			if($find){
				$this->error('该员工正在办理减员，无法增加险种');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status,ssr_id')->find();
			if($contract['status'] == 2){
				$this->error('合同已关闭，无法增加险种');
			}
			$contract_insurance = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id'],'insurance'=>$data['insurance'],'status'=>1])->find();
			if(!$contract_insurance){
				$this->error('合同无此险种，请重新选择');
			}			
			$increase_insurance = Db::name('system_increase_insurance')->where(['increase_id'=>$data['increase_id'],'insurance'=>$data['insurance']])->find();
			if(in_array($increase_insurance['status'],[1,2])){
				$this->error('该险种正在办理增加，请勿重复提交');
			}
			if($increase_insurance['status'] == 3){
				$this->error('该险种已在职，无法增加险种');
			}
			$day = date('d',time());   	   	
	    	$nextmonth = service_accounting_period();
			$re = Db::name('system_increase_insurance')->where(['id'=>$increase_insurance['id']])->update(['person_id'=>$increase['person_id'],'area'=>$contract_insurance['area'],'status'=>2,'start_date'=>$data['start_date'],'wage'=>$data['wage'],'company_base'=>$data['company_base'],'personal_base'=>$data['personal_base'],'account_period'=>$nextmonth,'is_deleted'=>0,'ssr_id'=>$contract['ssr_id']]);
			if($re){								
				$this->success('提交成功');							
			}else{
				$this->error('提交失败，请稍后再试');
			}
    	}else{
    		$id = $this->request->param('id');
			$this->id = $id;
			$this->insurances = get_option('insurance');
    	}
        $this->fetch();
    }
	
	
	
	/**
     * 减少险种
     */
    public function downsizing()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
			trim_array($data);
    		$increase = Db::name('system_increase')->where(['id'=>$data['increase_id'],'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->error('暂无员工信息');
			}
			$person = Db::name('system_person')->where(['id'=>$increase['person_id'],'company_id'=>$this->company['id']])->find();
			if(!$person || in_array($person['status'], [2,3])){
				$this->error('该员工不在职，无法减少险种');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id'],'status'=>1])->find();
			$contract_insurance = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id'],'insurance'=>$data['insurance'],'status'=>1])->count();
			if(!$contract_insurance){
				$this->error('合同无此险种，请重新选择');
			}	
			$insurance_result = Db::name('system_insurance_result')->where(['person_id'=>$person['id'],'insurance'=>$data['insurance'],'status'=>1,'increase_id'=>$data['increase_id']])->count();
			if(!$insurance_result){
				$this->error('该险种不在职，无法减少险种');
			}
			$find = Db::name('system_downsizing')->where(['person_id'=>$person['id'],'status'=>[1,3],'is_deleted'=>0])->find();
			if($find){
				$this->error('该员工正在办理减员，无法减少险种');
			}
			$downsizing_insurance = Db::name('system_downsizing_insurance')->where(['increase_id'=>$data['increase_id'],'insurance'=>$data['insurance'],'is_deleted'=>0])->find();
			if($downsizing_insurance['status'] == 1){
				$this->error('该险种正在办理减少，请勿重复提交');
			}
			if($downsizing_insurance['status'] == 2){
				$this->error('该险种不在职，无法减少险种');
			}
			$area = Db::name('system_increase_insurance')->where(['increase_id'=>$data['increase_id'],'insurance'=>$data['insurance']])->value('area');
			$code = number_rule_max(10);
			$nextmonth = after_month($data['end_date'],1);
			$arr = [
				'code' => $code,
				'increase_id' => $data['increase_id'],
				'company_id' => $this->company['id'],
				'contract_id' => $contract['id'],
				'person_id' => $person['id'],
				'insurance' => $data['insurance'],
				'status' => 1,
				'end_date' => $data['end_date'],
				'csr_id' => $increase['csr_id'],
				'type' => 2,
				'source' => 2,
				'area' => $area,
				'account_period' => $nextmonth,
				'ssr_id' => $contract['ssr_id']
			];
			$re = Db::name('system_downsizing_insurance')->insert($arr);
			if($re){
				save_number_rule_max(10);
				$this->success('提交成功');		
			}else{
				$this->error('提交失败，请稍后再试');
			}
    	}else{
    		$id = $this->request->param('id');
			$this->id = $id;
			$this->insurances = get_option('insurance');
    	}
        $this->fetch();
    }
	
	
	 /**
     * 增员
     */
    public function add()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
			trim_array($data);
			$validate = new IncreaseValidate;
    		if(!$validate->scene('examine')->check($data)){
	            $this->error($validate->getError());
	        }
			if(!is_idcard($data['id_number'])){
				$this->error('身份证号格式错误');
			}
			$person = Db::name('system_person')->where(['id_number'=>$data['id_number'],'status'=>1])->count();
			if($person){
				$this->error('该员工已在职，无法办理增员');
			}
			$count = Db::name('system_increase')->where(['id_number'=>$data['id_number'],'is_deleted'=>0,'status'=>1])->count();
			if($count){
				$this->error('该员工正在办理增员，请勿重复提交');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->find();
			if($contract['status'] == 2){
				$this->error('合同已关闭，无法办理增员');
			}
			if(in_array($contract['setmeal_type'],[2,3])){
				$person_count = Db::name('system_person')->where(['company_id'=>$this->company['id'],'status'=>1])->count();
				if($person_count >= $contract['people']){
					$this->error('人数套餐已达上限，无法增员');
				}
				$deduction = 0;
				$point = 0; 
			}else{
				$deduction = AdmIncService::deduction_check($this->company['id']);
				if(!$deduction){
					$this->error('服务点不足，无法办理增员');
				}
				$point = Db::name('system_service')->where(['is_special'=>2])->value('point'); 
			}
			//获取当前账期
			$start_date = service_accounting_period();
			if($start_date != $data['start_date']){
				$this->error('服务账期错误，无法办理增员');
			}
			$insert = [
				'code' => number_rule_max(7),
				'name' => $data['name'],
				'id_number' => $data['id_number'],
				'mobile' => $data['mobile'],
				'company_id' => $this->company['id'],
				'contract_id' => $contract['id'],
				'start_date' => $data['start_date'],
				'archives' => $data['archives'],
				'wage' => $data['wage'],
				'csr_id' => $this->company['csr_id'],
				'source' => 2,
				'deduction' => $deduction,
				'point' => $point
			];
			Db::startTrans();
			$re = Db::name('system_increase')->insertGetId($insert);
			if($re){
				$array = [];
				$insurance = get_option('insurance');
				foreach($insurance as $k=>$v){
		    		$array[$k]['increase_id'] = $re;
					$array[$k]['company_id'] = $this->company['id'];
		    		$array[$k]['insurance'] = $k;
					$array[$k]['csr_id'] = $this->company['csr_id'];
					$array[$k]['contract_id'] = $contract['id'];
		    		if(!empty($data['insurance_status'])){	    			
	    				if(!empty($data['insurance_status'][$k]) && $data['insurance_status'][$k] == 'on'){
	    					$array[$k]['status'] = 1;
	    				}else{
	    					$array[$k]['status'] = 0;
	    				}
		    		}else{
		    			$array[$k]['status'] = 0;
		    		}
					if(!empty($data['insurance_area'])){	    			
	    				if(!empty($data['insurance_area'][$k]) && $data['insurance_area'][$k]){
	    					$array[$k]['area'] = $data['insurance_area'][$k];
	    				}else{
	    					$array[$k]['area'] = 0;
	    				}
		    		}else{
		    			$array[$k]['area'] = 0;
		    		}
		    		if(!empty($data['insurance_start_date'])){	    			
	    				if(!empty($data['insurance_start_date'][$k]) && $data['insurance_start_date'][$k]){
	    					$array[$k]['start_date'] = $data['insurance_start_date'][$k];
	    				}else{
	    					$array[$k]['start_date'] = '';
	    				}
		    		}else{
		    			$array[$k]['start_date'] = '';
		    		}
					if(!empty($data['insurance_wage'])){	    			
	    				if(!empty($data['insurance_wage'][$k]) && $data['insurance_wage'][$k]){
	    					$array[$k]['wage'] = $data['insurance_wage'][$k];
	    				}else{
	    					$array[$k]['wage'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['wage'] = 0.00;
		    		}
		    		if(!empty($data['company_base'])){	    			
	    				if(!empty($data['company_base'][$k]) && $data['company_base'][$k]){
	    					$array[$k]['company_base'] = $data['company_base'][$k];
	    				}else{
	    					$array[$k]['company_base'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['company_base'] = 0.00;
		    		}
					if(!empty($data['personal_base'])){	    			
	    				if(!empty($data['personal_base'][$k]) && $data['personal_base'][$k]){
	    					$array[$k]['personal_base'] = $data['personal_base'][$k];
	    				}else{
	    					$array[$k]['personal_base'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['personal_base'] = 0.00;
		    		}		
		    	}
				$res = Db::name('system_increase_insurance')->insertAll($array);
			}			
			if($re && $res){
				Db::commit();
				save_number_rule_max(7);
				//扣除服务点数或次数
				AdmIncService::deduction($re);
				$this->success('努力提交中......', url('index/increase/addSuccess'));
			}else{
                Db::rollback();
                $this->error('提交失败，请稍后再试');
            }
    	}else{
    		$id = $this->request->get('id');
			$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->redirect('index/publicot/transition', ['info'=>'暂无员工信息','type'=>'1']);
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status')->find();
			if($contract['status'] == 2){
				$this->redirect('index/publicot/transition', ['info'=>'合同已关闭，无法进行增员','type'=>'1']);
			}
			$this->insurances = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id']])->field('insurance,area,status')->select();
			$this->increase = $increase;
    	}
    	
        $this->fetch();
    }
	
	
	/**
     * 减员
     */
    public function subtract()
	{
		if($this->request->isPost()){
			$data = $this->request->post();
			trim_array($data);
			$increase = Db::name('system_increase')->where(['id'=>$data['increase_id'],'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->error('暂无员工信息');
			}
			$person = Db::name('system_person')->where(['id'=>$increase['person_id'],'company_id'=>$this->company['id']])->find();
			if(!$person || in_array($person['status'], [2,3])){
				$this->error('该员工不在职，无法办理减员');
			}
			$find = Db::name('system_downsizing')->where(['person_id'=>$increase['person_id'],'status'=>1,'is_deleted'=>0])->find();
			if($find){
				$this->error('该员工正在办理减员，请勿重复提交');
			}
			$incins = Db::name('system_increase_insurance')->where(['person_id'=>$increase['person_id'],'status'=>[1,2],'is_deleted'=>0])->find();
			if($incins){
				$this->error('该员工正在增加险种，无法办理减员');
			}
			$count = Db::name('system_downsizing_insurance')->where(['person_id'=>$increase['person_id'],'is_deleted'=>0,'status'=>1])->count();
			if($count){
				$this->error('该员工正在减少险种，无法办理减员');
			}
			$insurances = Db::name('system_insurance_result')->where(['increase_id'=>$data['increase_id'],'status'=>1])->order('insurance asc')->column('insurance');
			if(empty($data['insurance'])){
				if($insurances){
					$this->error('数据异常，请刷新页面重新提交');
				}
			}else{
				if(array_diff($insurances, $data['insurance']) || array_diff($data['insurance'], $insurances)){
				    // 即相互都不存在差集，那么这两个数组就是相同的了，多数组也一样的道理
				    $this->error('数据异常，请刷新页面重新提交');
				}
			}
			
			
			$code = number_rule_max(9);
			$arr = [
				'code' => $code,
				'increase_id' => $data['increase_id'],
				'person_id' => $increase['person_id'],
				'company_id' => $increase['company_id'],
				'contract_id' => $increase['contract_id'],
				'end_date' => $data['end_date'],
				'csr_id' => $increase['csr_id'],
				'source' => 2,
				'deduction' => 0,
				'point'=> 0
			];
			Db::startTrans();
			$re = Db::name('system_downsizing')->insertGetId($arr);
			if($re){				
				if(!empty($data['insurance']) && $data['insurance']){
					$array = [];
					foreach($data['insurance'] as $k=>$v){
						$array[$k]['code'] = $code;
						$array[$k]['increase_id'] = $data['increase_id'];
						$array[$k]['company_id'] = $increase['company_id'];
						$array[$k]['contract_id'] = $increase['contract_id'];
						$array[$k]['person_id'] = $increase['person_id'];
						$array[$k]['insurance'] = $v;
						$array[$k]['desc'] = $data['insurance_desc'][$k];
						$array[$k]['end_date'] = $data['insurance_end_date'][$k];
						$array[$k]['csr_id'] = $increase['csr_id'];
						$array[$k]['type'] = 1;
						$array[$k]['source'] = 2;
						$array[$k]['area'] = Db::name('system_increase_insurance')->where(['increase_id'=>$data['increase_id'],'insurance'=>$v])->value('area');
					}
					$res = Db::name('system_downsizing_insurance')->insertAll($array);						
				}							
			}
			if($re){
				Db::commit();
				save_number_rule_max(9);
				//扣除服务点数或次数
				//AdmDowService::deduction($re);
				//所有的增员未处理删除
				Db::name('system_increase_insurance')->where(['increase_id'=>$data['increase_id'],'is_deleted'=>0,'status'=>[1,2]])->update(['is_deleted'=>1]);						
				$this->success('努力提交中......', url('index/staff/subSuccess'));
			}else{
                Db::rollback();
                $this->error('提交失败，请稍后再试');
            }
		}else{
			$id = $this->request->get('id');
			$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->redirect('index/publicot/transition', ['info'=>'暂无员工信息','type'=>'1']);
			}
			$person = Db::name('system_person')->where(['id'=>$increase['person_id'],'company_id'=>$this->company['id']])->find();
			if(!$person || in_array($person['status'], [2,3])){
				$this->redirect('index/publicot/transition', ['info'=>'暂无员工或员工不在职，无法减员','type'=>'1']);
			}
			$insurance = Db::name('system_insurance_result')->where(['increase_id'=>$id,'status'=>1])->order('insurance asc')->select();
			$this->list = $insurance;
			$this->increase = $increase;
			$this->insurances = get_option('insurance');
		}
		$this->fetch();
	}


	/**
     * 减员成功
     */
    public function subSuccess()
	{
		$this->fetch();
	}
	
	
	/**
     * 导出
     */
    public function export()
    {
        $data = $this->request->param();
    	$ids = explode(',', $data['id']);
		$list = ExportService::export_staff($ids,$this->company['id']);
    	toexcel($list['filename'],$list['titles'],$list['list']);  
    }
    
    
    /**
     * 导出全部
     */
    public function export_all()
    {
    	$ids = Db::name('system_company_person')->where(['company_id'=>$this->company['id']])->column('increase_id');
		$list = ExportService::export_staff($ids,$this->company['id']);
    	toexcel($list['filename'],$list['titles'],$list['list']);  
    }
	
}
